<?php
/**
 * 卡券货架，用户进入货架点击领取
 */
require_once('common.php');
$landingpage_url = 'https://api.weixin.qq.com/card/landingpage/create?access_token=';  //创建货架接口
//access_token
$accsss_token = get_access_token();

/*------------组装货架数据 start---------------*/
$data       = $_POST;
if(empty($data)){
    echo_Json(-1, '数据不能为空');
}
$banner     = $data['banner'];           //banner图片地址，建议尺寸640*300
$page_title = $data['page_title'];       //页面title，最多9个汉字
$can_share  = $data['can_share'] === false ? false : true;//是否允许分享
/* scene的值：
 *SCENE_NEAR_BY->附近,
 *SCENE_MENU->自定义菜单,
 *SCENE_QRCODE->二维码,
 *SCENE_ARTICLE->公众号文章,
 *SCENE_H5->h5页面,
 *SCENE_CARD_CUSTOM_CELL->卡券自定义cell
*/ 
$scene = $data['scene']; //投放页面的场景直，
//卡券列表数据组装
$card_id   = $data['card_id'];   //卡券id，多条使用逗号分隔
$thumb_url = $data['thumb_url']; //卡券缩略图。多个逗号分隔
if(empty($card_id) || empty($thumb_url)){
    echo_Json(-1, '货架内卡券数据不能为空');
}
$card_ids   = explode(',', $card_id);
$thumb_urls = explode(',', $thumb_url);
if(count($card_ids) != count($thumb_urls)){
    echo_Json(-1, '货架内卡券数据中card_id个数和thumb_url个数不一致');
}
foreach($card_ids as $k=>$card_id){
    $card_listArr[$k] = array(
        'card_id'   => $card_id,
        'thumb_url' => $thumb_urls[$k]
    );
}
$card_list = $card_listArr; //卡券列表
/*------------组装货架数据 end---------------*/
if(empty($banner)){
    echo_Json(-1, '货架banner图不能为空');
}
if(empty($page_title)){
    echo_Json(-1, '货架page_title不能为空');
}
if(empty($scene)){
    echo_Json(-1, '投放页面场景值不能为空');
}
//'banner' => 'https://dwz.cn/sa1132Z8',
//'thumb_url' => 'https://dwz.cn/S1kzSLlR'
$postData = array(
    'banner'     => $banner,
    'page_title'  => $page_title,
    'can_share' => $can_share,
    'scene'  => $scene,
    'card_list' => $card_list
);

$landingpageinfo = create_landingpage($landingpage_url.$accsss_token, $postData);
if($landingpageinfo['code'] != 0){
    echo_Json($landingpageinfo['code'], '货架创建失败');
}else{
    $info['url'] = $landingpageinfo['url'];
    $info['page_id'] = $landingpageinfo['page_id'];
    echo_Json($landingpageinfo['code'], '货架创建成功', $info);
}

function create_landingpage($url, $data){
    $landingpage_Arr = jsonpostJson($url, $data, true); //post请求
    if($landingpage_Arr['errcode'] != 0){
        $result = array(
            'code' => $landingpage_Arr['errcode'],
        );
    }else{
        $result = array(
            'code' => 0,
            'url'  => $landingpage_Arr['url'],        //货架地址
            'page_id' => $landingpage_Arr['page_id']  //货架ID
        );
    }
    return $result;
}
